package org.netwia.networks;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.netwia.utils.ValidationUtils;

/**
 * Implementation of the input provider which picks up the input from the remote network connector. 
 * 
 * @author radek.hecl
 *
 * @param <T> type of the network parameter
 */
public class RemoteProxyInputProvider<T> implements InputProvider<T> {

    /**
     * Builder object.
     * 
     * @param <T> type of the network parameter
     */
    public static class Builder<T> {

        /**
         * Source for the input.
         */
        private RemoteNetworkConnector<T> source;

        /**
         * Name of the package to query for.
         */
        private String packageName;
        
        /**
         * Set source for the input.
         * 
         * @param source source for the input
         * @return this instance
         */
        public Builder<T> setSource(RemoteNetworkConnector<T> source) {
            this.source = source;
            return this;
        }
        
        /**
         * Sets name of the package to query for.
         * 
         * @param packageName name of the package to query for
         * @return this instance
         */
        public Builder<T> setPackageName(String packageName) {
            this.packageName = packageName;
            return this;
        }
        
        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public RemoteProxyInputProvider<T> build() {
            return new RemoteProxyInputProvider<T>(this);
        }
    }

    /**
     * Source for the input.
     */
    private RemoteNetworkConnector<T> source;

    /**
     * Name of the package to use.
     */
    private String packageName;

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public RemoteProxyInputProvider(Builder<T> builder) {
        source = builder.source;
        packageName = builder.packageName;
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    private void guardInvariants() {
        ValidationUtils.guardNotNull(source, "source cannot be null");
        ValidationUtils.guardNotEmpty(packageName, "packageName cannot be empty");
    }

    @Override
    public boolean isNextInputReady() {
        return source.isNextInputReady(packageName);
    }

    @Override
    public T getNextInput() {
        return source.getNextInput(packageName);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
